from flask import Flask
from flask_jwt_extended import JWTManager
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from .config import Config
from .routes import register_routes
from .auth.recommend import *
from .models import *
db = MongoEngine()
jwt = JWTManager()

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    db.init_app(app, config=app.config.get('MONGODB_SETTINGS'))
    init_redis(app)

    # 初始化 JWT
    jwt = JWTManager(app)
    @jwt.user_identity_loader
    def user_identity_lookup(user):
        return str(user.id)

    @jwt.user_lookup_loader
    def user_lookup_callback(_jwt_header, jwt_data):
        identity = jwt_data["sub"]
        return User.objects(id=identity).first()

    # 初始化 Limiter
    limiter = Limiter(
        get_remote_address,
        app=app,
    )

    # 注册路由
    register_routes(app, limiter, jwt)

    return app